import 'package:ble_helper_plugin/library.dart';
import 'package:ble_helper_plugin/src/ble_manager.dart';
import 'package:flutter/widgets.dart';

// 蓝牙连接助手类
class BluetoothSendHelper<I extends BluetoothInterceptor,
    S extends HandlerSettingsBase> {
  // 蓝牙发送处理器
  final S handlerSettings;

  // 蓝牙请求响应拦截器
  final I? bluetoothInterceptor;

  // 构造函数
  BluetoothSendHelper(
    this.handlerSettings, {
    this.bluetoothInterceptor,
  });

  // 获取蓝牙管理器
  final BluetoothManager _manager = BluetoothManager();

  // 监听响应数据（该数据为原始数据）
  Stream<List<int>>? get notifyStream => _manager.notifyStream;

  // 共公蓝牙当前连接状态
  Stream<CustomBluetoothConnectState> get bluetoothConnectState =>
      _manager.bluetoothConnectState;

  // 发送请求并接收响应
  Future<List<int>> sendRequest(
    List<int> requestData, {
    bool withoutResponse = false,
    Duration? timeout,
  }) {
    return _manager.write(
      handlerSettings,
      requestData,
      withoutResponse: withoutResponse,
      bluetoothInterceptor: bluetoothInterceptor,
      timeout: timeout,
    );
  }

  // 清空等待请求
  void clearWaitingRequests() {
    handlerSettings.timeoutHelper.requestQueue.clear();
    handlerSettings.timeoutHelper.responseStreamMap.clear();
    debugPrint('【$runtimeType】清空等待请求');
  }
}
